package cn.wolfcode.shop.service.impl;

import cn.wolfcode.shop.domain.OrderInfo;
import cn.wolfcode.shop.exception.GlobalException;
import cn.wolfcode.shop.result.CodeMsg;
import cn.wolfcode.shop.service.*;
import cn.wolfcode.shop.vo.GoodVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.jms.JMSException;

/**
 * 在一个类的内部,方法A如果有事务,调用同类里的拥有事务的方法B,则B的事务失效,使用A的事务
 * 若方法A没有事务,调用有事务的方法B,则B事务同样失效,只有在外部调用时,事务才有效
 */
@Service
@Transactional
public class SeckillServiceImpl implements ISeckillService{
    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Override
    public String doSeckill(Long userId, Long goodId) {
        GoodVo goodVo = seckillGoodService.getCacheByGoodId(goodId);
        return createOrder(userId,goodVo).getOrderNo();
    }


    public OrderInfo createOrder(Long userId,GoodVo goodVo){
        int count = seckillGoodService.reduceStockCount(goodVo.getGoodId());
        if(count > 0){//减库存成功,才能正常生成订单等信息
            OrderInfo orderInfo = orderInfoService.createOrder(userId, goodVo);
            seckillOrderService.createSeckillOrder(userId,goodVo.getGoodId(),orderInfo.getOrderNo());

            return orderInfo;
        }else {//影响行数<=0, 说明库存卖完
            throw new GlobalException(CodeMsg.SECKILL_OVER);
        }
    }

    public int reduceStockCount(Long goodId){
        return seckillGoodService.reduceStockCount(goodId);
    }

    @Override
    public void syncStock(Long goodId) throws JMSException {
        seckillGoodService.syncStock(goodId);
    }
}
